package com.atguigu.juc.day01.homework;

import java.util.concurrent.TimeUnit;

public class DemoSaleTicket {

    // 票的库存
    private int stock = 100;

    // 声明一个方法专门负责卖票
    public synchronized void saleTicket() {
        try {
            if (stock > 0) {
                System.out.println(Thread.currentThread().getName() + "号窗口卖票一张，还剩：" + --stock + " 张。");
                TimeUnit.MILLISECONDS.sleep(300);
            } else {
                System.out.println(Thread.currentThread().getName() + "号窗口报告：票已卖完。");
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {

        // 1、创建当前类的对象
        DemoSaleTicket demo = new DemoSaleTicket();

        // 2、创建三个线程代表卖票的三个窗口
        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                demo.saleTicket();
            }
        }, "thread-a").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                demo.saleTicket();
            }
        }, "thread-b").start();

        new Thread(()->{
            for (int i = 0; i < 40; i++) {
                demo.saleTicket();
            }
        }, "thread-c").start();

    }

}
